package controller

import (
	"quick-go/model"
	"strconv"

	"github.com/gin-gonic/gin"
)

type UserController struct{}

func (u UserController) DeleteUser(c *gin.Context) {
	idStr := c.Param("id")
	id, _ := strconv.Atoi(idStr)
	err := model.DeleteUser(id)
	if err != nil {
		ReturnError(c, 4001, "delete user error")
		return
	}
	ReturnSuccess(c, 200, "id", "delete user success", 1)
}

func (u UserController) UpdateUser(c *gin.Context) {

	idStr := c.Param("id")
	id, _ := strconv.Atoi(idStr)
	username := c.PostForm("name")
	ageStr := c.DefaultPostForm("age", "18")
	age, _ := strconv.Atoi(ageStr)
	err := model.UpdateUser(id, username, age)
	if err != nil {
		ReturnError(c, 4001, "update user error")
		return
	}
	ReturnSuccess(c, 200, "id", "update user success", 1)
}

func (u UserController) CreateUser(c *gin.Context) {

	username := c.PostForm("name")
	ageStr := c.DefaultPostForm("age", "18")
	age, _ := strconv.Atoi(ageStr)

	id, err := model.CreateUser(username, age)

	if err != nil {
		ReturnError(c, 4001, "create user error")
		return
	}
	ReturnSuccess(c, 200, id, "create user success", 1)
}

func (u UserController) GetUserOne(c *gin.Context) {
	// ReturnSuccess(c, 200, "id", "user id", 1)
	idStr := c.Param("id")
	// ReturnSuccess(c, 200, id, "user id", 1)
	id, _ := strconv.Atoi(idStr)
	user, _ := model.GetUserByID(id)
	ReturnSuccess(c, 200, user.ID, user.Name, 1)
}

func (u UserController) GetUserList(c *gin.Context) {
	ReturnError(c, 4001, "user list error")
}

func (u UserController) GetUserLT3(c *gin.Context) {
	users, err := model.GetUserLT3()
	if err != nil {
		ReturnError(c, 4001, "get user list error")
		return
	}
	ReturnSuccess(c, 200, users, "获取 id 小于3的用户列表成功", len(users))

}
